<?php
namespace App\Api\Appfc114;

use PhalApi\Api;
use PhalApi\Exception\BadRequestException;
use JiaweiXS\WeApp\WeApp;
use Auth\Api\Token as Token;
use App\Domain\Appfc114\User as DomainUser;
use App\Domain\Appfc114\QueryScore as QueryScore;


/**
 * 用户接口服务
 *
 * @author: dogstar <chanzonghuang@gmail.com> 2014-10-04
 */

class User extends Api {

    /**
     * token对象
     */
    protected $token;
    private $appid;
    private $sessionKey;

    public function __construct()
    {
        //允许所有域名发起的跨域请求
        header('Access-Control-Allow-Origin: *');  //支持全域名访问，不安全，部署后需要固定限制为客户端网址
        //header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作
        //header('Access-Control-Allow-Headers:Authorization,content-type');  //响应头 请按照自己需求添加。
        //$this->di = \PhalApi\DI();
        $this->token = new Token();
    }

	public function getRules() {
        return array(
            'getUser' => [],
            'login'=>['openid'=>['name' => 'openid', 'type'=>'string', 'require' => true, 'desc' => 'openid']],
            'setUserInfo'=>[],
            'bindMobile'=>["mobile"=>['name' => 'mobile', 'type'=>'string', 'require' => true, 'desc' => 'mobile']],
            'getUserPhone'=>[],
            'getUserScore'=>[],
        );
	}


    /**
	 * 获取用户信息
     * @desc 返回用户相关信息<br>Authorization Type: Bear Token<br>"headers" : {'Authorization': 'Bearer '+ token}
     * @return array userInfo 用户信息
	 * @return int time 当前时间戳
	 */
	public function getUser() {
        $this->user = $this->token->checkToken();
        error_log("getDetail!", 0);

        $user_id =  $this->user['user_id'];
        $user = new DomainUser();
        $userInfo = $user->getDetail($user_id,"id");
        return $userInfo;
	}

    /**
     * 设置用户信息
     * @desc 返回用户相关信息
     * @return array userInfo 用户信息
     * @return int time 当前时间戳
     */
    public function setUserInfo() {
        $this->user = $this->token->checkToken();
        error_log("setUserInfo!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $user = new DomainUser();
        $id = $user->update($params,$this->user["user_id"]);

        return $id;
    }

    /**
     * 绑定用户电话
     * @desc 返回用户相关信息
     * @return array userInfo 用户信息
     * @return int time 当前时间戳
     */
    public function bindMobile() {
        $this->user = $this->token->checkToken();
        error_log("bindmobile!", 0);

        $params =  \PhalApi\DI()->request->getAll();
        $user = new DomainUser();
        $id = $user->update($params,$this->user["user_id"]);

        return $id;
    }

    /**
     * 得到用户微信电话
     * @desc 返回用户微信电话
     * @return obj data 用户电话
     * @return int time 当前时间戳
     */
    public function getUserPhone() {
        // 接收信息
        $params = \PhalApi\DI()->request->getAll();
        $encryptedData = $params['encryptedData']; // 加密数据
        $iv = $params['iv']; // 加密算法
        $this->sessionKey = $params['sessionKey']; // 会话密钥
        if($encryptedData == '' || $iv == ''){
            error_log("手机号码没获取!", 0);
        }else{
            $rlt = $this->decryptData($encryptedData, $iv);
        }
        return $rlt;
    }

    /**
     * 得到用户积分
     * @desc 返回用户积分
     * @return int score 用户积分
     * @return int time 当前时间戳
     */
    public function getUserScore() {
        $this->user = $this->token->checkToken();
        error_log("getUserScore!", 0);

        $score= new QueryScore();
        $num = $score->userScore($this->user["user_id"]);

        return $num;
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv)
    {
        if (strlen($this->sessionKey) != 24) {
            error_log("getPhone!", 0);
        }
        $aesKey=base64_decode($this->sessionKey);

        if (strlen($iv) != 24) {
            error_log("getPhone!", 0);
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );

        return $dataObj;
    }

}
